package com.dge.app.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.VibrateUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.chad.library.adapter.base.dragswipe.QuickDragAndSwipe
import com.chad.library.adapter.base.dragswipe.listener.OnItemDragListener
import com.chad.library.adapter.base.dragswipe.listener.OnItemSwipeListener
import com.dge.app.R
import com.dge.app.adapters.FunctionListAdapter
import com.dge.app.adapters.StatisticPanelAdapter
import com.dge.app.bean.StatisticsBean
import com.dge.app.databinding.ActivityMainBinding
import com.dge.common.base.view.BaseActivity
import com.dge.common.common.Constants
import com.dge.common.common.URLConstants
import com.dge.common.common.UserInfoMgr
import com.dge.common.extentions.*
import com.dge.common.utils.GsonUtils
import com.dge.common.utils.RecyclerViewDivider
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import timber.log.Timber
import java.util.Collections

// @Route(path = Constants.ACTIVITY_URL_MAIN)
class MainActivity : BaseActivity<ActivityMainBinding>() {
    val funAdapter: FunctionListAdapter by lazy { FunctionListAdapter(arrayListOf()) }
    val statisticAdapter: StatisticPanelAdapter by lazy { StatisticPanelAdapter(arrayListOf()) }
    var lastVisibleDeleteView: View? = null
    private val statisticNames = arrayListOf<String>()

    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initViews()
        initListeners()
    }

    private fun initViews() {
        // binding.tvPercent.text = Spans.builder().text("71.24").size(24).text("%").size(14).build()
        initHotSearch()
        initFunctions()
        initBanner()
        initStatistics()
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun initListeners() {
        binding.rvFunctions.itemClick<String> { data, view, position ->
            val item = data[position]
            Timber.i("点击了 = $item")
            if (item == "更多") {
                val intent = Intent(this, WebViewActivity::class.java)
                intent.putExtra(
                    WebViewActivity.EXTRA_URL,
                    "${URLConstants.URL_USER_BASE}/index"
                )
                intent.putExtra(WebViewActivity.EXTRA_TITLE, "应用库")
                intent.putExtra(WebViewActivity.EXTRA_FUN_JSON_DATA, UserInfoMgr.functionData)
                startActivityForResult(intent, object : OnActivityCallback {
                    override fun onActivityResult(resultCode: Int, data: Intent?) {
                        Timber.i("onActivityResult 概览视窗配置")
                        funAdapter.submitList(getFuncData())
                        saveFunctionChange()
                    }
                })
            } else {
                val intent = Intent(this, WebViewActivity::class.java)
                intent.putExtra(
                    WebViewActivity.EXTRA_URL,
                    "${URLConstants.URL_USER_BASE}/applet"
                )
                intent.putExtra(WebViewActivity.EXTRA_TITLE, item)
                startActivity(intent)
            }
        }
        binding.rvFunctions.itemLongClick<String> { data, view, position ->
            // Timber.i("长按了 = ${data[position]}")
            if (data[position] != "更多") {
                val deleteView = (view as ViewGroup).getChildAt(1)
                if (lastVisibleDeleteView != deleteView) lastVisibleDeleteView?.gone()
                deleteView.visible()
                lastVisibleDeleteView = deleteView
            }
        }
        funAdapter.addOnItemChildClickListener(R.id.ivDelete) { adapter, view, position ->
            adapter.removeAt(position)
            saveFunctionChange()
            if (adapter.itemCount == 9) {
                funAdapter.notifyItemChanged(adapter.itemCount - 1)
            }
        }
        binding.icMore.singleClick {
            val intent = Intent(this, WebViewActivity::class.java)
            intent.putExtra(
                WebViewActivity.EXTRA_URL,
                "${URLConstants.URL_USER_BASE}/overview"
            )
            intent.putExtra(WebViewActivity.EXTRA_TITLE, "概览视窗配置")
            intent.putExtra(WebViewActivity.EXTRA_FUN_JSON_DATA, UserInfoMgr.statisticsData)
            startActivityForResult(intent, object : OnActivityCallback {
                override fun onActivityResult(resultCode: Int, data: Intent?) {
                    Timber.i("onActivityResult 概览视窗配置")
                    val items = getStatisticsData()
                    statisticAdapter.setStatisticNames(statisticNames)
                    statisticAdapter.submitList(items)
                }
            })
        }
        binding.scrollView.setOnTouchListener { v, event ->
            //点击空白区域，隐藏功能删除按钮
            if (lastVisibleDeleteView?.visibility != View.GONE) {
                lastVisibleDeleteView?.gone()
                lastVisibleDeleteView = null
            }
            false
        }
    }

    private fun saveFunctionChange() {
        // val bean = GsonUtils.gson.fromJson(UserInfoMgr.functionData, FunctionsBean::class.java)
        // bean.functions.clear()
        // bean.functions.addAll(funAdapter.items)
        UserInfoMgr.functionData = GsonUtils.gson.toJson(funAdapter.items)
        UserInfoMgr.saveUserInfo(Constants.firstIn)
    }

    private fun saveStatisticsChange() {
        val bean = StatisticsBean()
        bean.names.addAll(statisticNames)
        bean.urls.addAll(statisticAdapter.items)
        UserInfoMgr.statisticsData = GsonUtils.gson.toJson(bean)
        UserInfoMgr.saveUserInfo(Constants.firstIn)
    }

    /**
     * 模拟功能面板数据获取
     */
    private fun getFuncData(): ArrayList<String> {
        val functionData = GsonUtils.gson.fromJson(UserInfoMgr.functionData, Array<String>::class.java).toCollection(ArrayList())
        return if (functionData.size < 10) {
            if (functionData.isNotEmpty()) {
                if (functionData.last() != "更多") {
                    functionData.add("更多")
                }
            } else {
                functionData.add("更多")
            }
            functionData
        } else {
            functionData.add(9, "更多")
            ArrayList(functionData.subList(0, 10))
        }
    }

    /**
     * 模拟统计面板数据获取
     */
    private fun getStatisticsData(): ArrayList<String> {
        val data = GsonUtils.gson.fromJson(UserInfoMgr.statisticsData, StatisticsBean::class.java)
        statisticNames.clear()
        statisticNames.addAll(data.names)
        Timber.i("data = $data")
        return data.urls
    }

    /**
     * 热搜
     */
    private fun initHotSearch() {
        val array = arrayListOf("应用资源", "组件资源", "数据资源", "GIS图层")
        binding.rvHotSearch.horizontal()
        binding.rvHotSearch.divider(Color.TRANSPARENT, 12.dp)
        binding.rvHotSearch.bindData(array, R.layout.item_hot_search) { holder, item, position ->
            holder.getView<TextView>(R.id.tvHotSearch).text = item
        }
    }

    /**
     * 统计面板
     */
    private fun initStatistics() {
        val data = getStatisticsData()
        binding.rvStatistic.vertical()
        binding.rvStatistic.divider(Color.TRANSPARENT, 12.dp)
        binding.rvStatistic.adapter = statisticAdapter
        statisticAdapter.setStatisticNames(statisticNames)

        statisticAdapter.submitList(data)
        val quickDragAndSwipe = QuickDragAndSwipe()
            .setDragMoveFlags(ItemTouchHelper.UP or ItemTouchHelper.DOWN)
            .setSwipeMoveFlags(ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT)
        // 拖拽监听
        val listener: OnItemDragListener = object : OnItemDragListener {
            var startPos = 0
            override fun onItemDragStart(viewHolder: RecyclerView.ViewHolder?, pos: Int) {
                startPos = pos
                VibrateUtils.vibrate(70)
            }

            override fun onItemDragMoving(
                source: RecyclerView.ViewHolder,
                from: Int,
                target: RecyclerView.ViewHolder,
                to: Int
            ) {
            }

            override fun onItemDragEnd(viewHolder: RecyclerView.ViewHolder, pos: Int) {
                if (startPos != pos) {
                    Collections.swap(statisticNames, startPos, pos)
                    saveStatisticsChange()
                }
            }
        }
        val swipeListener: OnItemSwipeListener = object : OnItemSwipeListener {
            override fun onItemSwipeStart(viewHolder: RecyclerView.ViewHolder?, bindingAdapterPosition: Int) {
                // Log.d(TAG, "onItemSwipeStart")
            }

            override fun onItemSwipeEnd(viewHolder: RecyclerView.ViewHolder, bindingAdapterPosition: Int) {
                // Log.d(TAG, "onItemSwipeEnd")
            }

            override fun onItemSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int, bindingAdapterPosition: Int) {
                statisticNames.removeAt(bindingAdapterPosition)
                saveStatisticsChange()
            }

            override fun onItemSwipeMoving(
                canvas: Canvas,
                viewHolder: RecyclerView.ViewHolder,
                dX: Float,
                dY: Float,
                isCurrentlyActive: Boolean
            ) {
                // Log.d(TAG, "onItemSwipeMoving")
            }
        }
        // 滑动事件
        quickDragAndSwipe.attachToRecyclerView(binding.rvStatistic)
            .setDataCallback(statisticAdapter)
            .setItemDragListener(listener)
            .setItemSwipeListener(swipeListener)
    }

    /**
     * 功能列表
     */
    private fun initFunctions() {
        val layoutManager = GridLayoutManager(this, 5, GridLayoutManager.VERTICAL, false)
        layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                return 1
            }
        }
        binding.rvFunctions.layoutManager = layoutManager
        val decoration = RecyclerViewDivider(this, RecyclerView.VERTICAL)
        decoration.setDrawable(GradientDrawable().apply {
            setColor(Color.TRANSPARENT)
            shape = GradientDrawable.RECTANGLE
            setSize(12.dp, 12.dp)
        })
        binding.rvFunctions.addItemDecoration(decoration)
        // 拖拽监听
        val quickDragAndSwipe = object : QuickDragAndSwipe() {
            override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
                if (viewHolder.adapterPosition == (funAdapter.itemCount - 1)) return 0 //禁用最后一个
                val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN or
                        ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
                val swipeFlags = 0
                return makeMovementFlags(dragFlags, swipeFlags)
            }

            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean {
                val toPosition = target.bindingAdapterPosition
                if (toPosition == (funAdapter.itemCount - 1)) return false //最后一个不交换
                return super.onMove(recyclerView, viewHolder, target)
            }
        }
        binding.rvFunctions.adapter = funAdapter
        funAdapter.submitList(getFuncData())
        // 拖拽监听
        val listener: OnItemDragListener = object : OnItemDragListener {
            var startPos = 0
            override fun onItemDragStart(viewHolder: RecyclerView.ViewHolder?, pos: Int) {
                startPos = pos
                VibrateUtils.vibrate(70)
                // Timber.i("drag start")
            }

            override fun onItemDragMoving(
                source: RecyclerView.ViewHolder,
                from: Int,
                target: RecyclerView.ViewHolder,
                to: Int
            ) {
                // Timber.i("move from: " + source.bindingAdapterPosition + " to: " + target.bindingAdapterPosition)
            }

            override fun onItemDragEnd(viewHolder: RecyclerView.ViewHolder, pos: Int) {
                // Timber.i("drag end")
                if (startPos != pos) {
                    saveFunctionChange()
                    val deleteView = (viewHolder.itemView as ViewGroup).getChildAt(1)
                    deleteView.gone()
                    lastVisibleDeleteView = null
                }
            }
        }
        // 滑动事件
        quickDragAndSwipe.attachToRecyclerView(binding.rvFunctions)
            .setDataCallback(funAdapter)
            .setItemDragListener(listener)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        //采用moveTaskToBack 方法，当用户点击返回时，将APP隐藏到后台。再次打开的时候，APP进程还存在，不打开启动界面 ，直接进入主页。
        if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
            moveTaskToBack(true)
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun initBanner() {
        val dummyImages = arrayListOf(R.mipmap.bg_banner, R.mipmap.bg_banner)
        binding.banner.setAdapter(object : BannerImageAdapter<Int>(dummyImages) {
            override fun onBindView(holder: BannerImageHolder, data: Int, position: Int, size: Int) {
                Glide.with(holder.itemView)
                    .load(data)
                    .apply(RequestOptions.bitmapTransform(RoundedCorners(8.dp)))
                    .into(holder.imageView)
            }
        })
            .addBannerLifecycleObserver(this).indicator = CircleIndicator(this)
    }
}